<template>
  <div>
    <el-container class="container-box">
      <el-container class="">
        <el-header class="container-header">
          <el-tabs id="p20" type="border-card" v-model="activeName">
            <el-tab-pane
              :lazy="true"
              :name="TABSNAME.public"
              label="公开专题"
            ></el-tab-pane>
            <el-tab-pane
              :lazy="true"
              :name="TABSNAME.team"
              label="团队专题"
            ></el-tab-pane>
            <el-tab-pane
              :lazy="true"
              :name="TABSNAME.evaluation"
              label="历年真题"
            ></el-tab-pane>
            <el-tab-pane
              :lazy="true"
              :name="TABSNAME.preliminaryTest"
              label="初试专题"
            ></el-tab-pane>
            <el-tab-pane
              :lazy="true"
              :name="TABSNAME.myQuestionBank"
              label="我的专题"
            ></el-tab-pane>
            <el-tab-pane
              v-if="tenant_id || myteam.tenant_id === tenant_id"
              :lazy="true"
              v-for="(v, k) in questionBankLabels"
              :label="v.name"
              :name="`${dynamicTabStartWidth}${v.ID}`"
              :key="v.ID"
            ></el-tab-pane>
            <!-- 搜索条件 -->
            <div class="container-header-form">
              <div v-show="activeTabDesc">
                <el-text size="small" type="info">
                  <el-icon>
                    <InfoFilled />
                  </el-icon>
                  {{ activeTabDesc }}
                </el-text>
              </div>
              <el-form class="" label-position="left">
                <el-form-item
                  class="container-header-form-item"
                  size="default"
                  label="查找专题"
                  :label-width="70"
                >
                  <div class="container-header-form-item-flex">
                    <div>
                      <el-input
                        size="default"
                        :style="{ width: '250px' }"
                        v-model.lazy="_formInline.name"
                        placeholder="输入查找专题名"
                      >
                      </el-input>
                      <el-button
                        class="container-header-form-search-btn"
                        @click="search"
                        type="primary"
                        size="default"
                      >
                        搜索
                      </el-button>
                    </div>
                    <router-link
                      v-if="
                        activeName == TABSNAME.myQuestionBank &&
                        getuser?.isAdmin
                      "
                      custom
                      :to="{ name: '修改我的专题', params: { ID: 0 } }"
                      v-slot="{ navigate }"
                    >
                      <el-button @click="navigate" type="primary" size="default"
                        >+ 创建我的专题</el-button
                      >
                    </router-link>
                    <div v-if="activeName == TABSNAME.team && getuser?.isAdmin">
                      <el-button
                        @click="dialogVisible = true"
                        type="primary"
                        size="default"
                        >+ 导入团队专题</el-button
                      >
                    </div>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </el-tabs>
        </el-header>
        <el-main class="container-content">
          <el-scrollbar>
            <el-pagination
              class="pager margin0"
              size="default"
              :page-size="limit"
              :total="getquestionbankcount"
              :page-sizes="pageSizes"
              @size-change="handleSizeChange"
              @current-change="changePage"
              layout="total,sizes,prev, pager, next"
              :current-page="Math.floor(offset / limit) + 1"
            >
            </el-pagination>
            <el-table
              row-class-name="cursor-pointer"
              :data="getquestionbank"
              stripe
              v-loading="loading"
              width="100%"
              @row-click="rowClick"
            >
              <template v-slot:empty>
                <el-empty
                  image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png"
                />
              </template>
              <el-table-column width="90" prop="ID" label="编号" />
              <el-table-column
                show-overflow-tooltip
                width="350"
                prop="name"
                label="题单"
              />
              <el-table-column
                show-overflow-tooltip
                :tooltip-formatter="
                  ({ row, column, cellValue }) =>
                    row.questionlabel
                      .map(
                        (vo) => getlabel.find((e) => e.ID === vo.labelid)?.name
                      )
                      .join(', ')
                "
                width=""
                prop="questionlabel"
                label="包含题目标签"
              >
                <template #default="{ row, column }">
                  <el-tag
                    class="question-intable-label"
                    text
                    type="primary"
                    effect="plain"
                    size="default"
                    v-for="(vo, keys) in row.questionlabel"
                    v-text="getlabel.find((e) => e.ID === vo.labelid)?.name"
                    :key="`1-${keys}`"
                  >
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column
                width="160"
                prop="questionquestionbank"
                align="center"
                label="我的提交/总题目数"
              >
                <template #default="{ row, column }">
                  {{ row.count || 0 }} / {{ row.questionquestionbank?.length }}
                </template>
              </el-table-column>
              <!-- <el-table-column width="110" prop="count" align="center" label="我提交题目数" /> -->
              <el-table-column
                v-if="activeName !== TABSNAME.preliminaryTest"
                width="200"
                prop="ACcount"
                label="我的通过率"
              >
                <template #default="{ row, column }">
                  <el-progress
                    :text-inside="true"
                    :stroke-width="18"
                    :percentage="getACRate(row)"
                    :color="customColors"
                  />
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                width="160"
                prop=""
                v-if="activeName === TABSNAME.myQuestionBank"
                label="操作"
              >
                <template #default="{ row, column }">
                  <router-link
                    custom
                    :to="{ name: '修改我的专题', params: { ID: row.ID } }"
                    v-slot="{ navigate }"
                  >
                    <el-button
                      size="default"
                      type="primary"
                      @click.stop="navigate"
                      >编辑</el-button
                    >
                  </router-link>
                  <el-button
                    size="default"
                    type="primary"
                    @click.stop="del(row.ID)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
              class="pager"
              size="default"
              :page-size="limit"
              :total="getquestionbankcount"
              :page-sizes="pageSizes"
              @size-change="handleSizeChange"
              @current-change="changePage"
              layout="total,sizes,prev, pager, next"
              :current-page="Math.floor(offset / limit) + 1"
            >
            </el-pagination>
          </el-scrollbar>
        </el-main>
      </el-container>
    </el-container>
    <!-- 导入团队专题 -->
    <el-dialog
      v-model="dialogVisible"
      v-if="dialogVisible"
      title="选择专题"
      width="840px"
      height="90vh"
      top="0"
      :before-close="beforeClose"
    >
      <template #header>
        <span class="icon-text el-dialog__header-title">
          <el-icon class="text-primary">
            <Guide />
          </el-icon>
          选择专题
        </span>
      </template>
      <Addselectquestionbank :addclick="addclick" :teamid="teamId">
      </Addselectquestionbank>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import { uniqBy } from "lodash-es";
import { assign, debounce } from "underscore";
import { computed, inject, onMounted, reactive, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import {
  Iobj,
  asyncaddquestionbankteam,
  asyncdelquestionbank,
  asyncgetmyquestionbank,
  asyncselectquestionbank,
  asyncselectquestionlabel,
} from "../../../api/index";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { findpid } from "../../../util/code";
import Addselectquestionbank from "./addselectquestionbank.vue";
import { LabelType } from "@/util/data";

// 码客行
const tenant_id = inject<string | undefined>("tenant_id", undefined);

// AC 率颜色
const customColors = [
  { color: "#e83828", percentage: 20 },
  { color: "#f0830ac", percentage: 40 },
  { color: "#82bd1c", percentage: 60 },
  { color: "#1ecbb4", percentage: 80 },
  { color: "#4683fa", percentage: 100 },
];
// tabs
enum TABSNAME {
  public = "public",
  team = "team",
  evaluation = "evaluation", // 历年真题
  preliminaryTest = "preliminaryTest", // 初试专题
  myQuestionBank = "myQuestionBank", // 我的专题
}
// tabs 切换 参数配置
const tabsQueryCfg = {
  [TABSNAME.public]: {
    isteam: 0,
    usertype: "user",
    purpose: "",
    order: "top",
    sortable: "asc",
    istest: 0,
    desc: "公开专题：该专题是系统公开专题，所有人都可以访问",
  },
  [TABSNAME.team]: {
    isteam: 1,
    istest: 0,
    desc: "团队专题：该专题是团队内部指定专题，由团队管理员从“我的专题”中授权开放至团队",
  },
  [TABSNAME.evaluation]: {
    purpose: "能力测评",
    isteam: 0,
    order: "ID",
    sortable: "asc",
    istest: 1,
    desc: "历年真题：往年CSP/NOIP真题，可作为赛前模拟",
  },
  [TABSNAME.preliminaryTest]: {
    purpose: "初试练习",
    isteam: 0,
    order: "ID",
    sortable: "asc",
    istest: 0,
    desc: "初试专题：适合CSP/NOIP第一轮的初试题目，以知识点分类汇总",
  },
  [TABSNAME.myQuestionBank]: {
    desc: "我的专题：用于我个人收藏的专题。如果是团队管理员，可以将我的专题开放至团队",
  },
  // 动态Tab 搜索条件（通过计算属性动态生成）
  getDynamicConfig: (labelId: number | undefined) => {
    const labelName = getLabelNameById(labelId); // 获取标签名称
    return {
      label: [labelId],
      desc: `专题标签：${labelName}`,
    };
  },
};
const activeTabDesc = computed(() => {
  if (isDynamicTab.value) {
    const labelId = currentLabelId.value;
    return tabsQueryCfg.getDynamicConfig(labelId)?.desc || "";
  }
  return tabsQueryCfg[activeName.value]?.desc || "";
});
// 动态Tab
const dynamicTabStartWidth = "label_";
const isDynamicTab = computed(() =>
  activeName.value.startsWith(dynamicTabStartWidth)
);
const currentLabelId = computed(() =>
  isDynamicTab.value ? Number(activeName.value.split("_")[1]) : undefined
);
const questionBankLabels = computed(() => {
  // e.tenant_id == tenant_id 数据库中没有值是null 要用 ==
  const d = findpid(
    getlabel.value.filter((e) => {
      return (
        e.type === LabelType.QUESTIONBANK &&
        tenant_id &&
        e.tenant_id == tenant_id
      );
    })
  );
  return d;
});
// 获取标签的名称而不是ID
const getLabelNameById = (id: number | undefined) => {
  const label = questionBankLabels.value.find((label) => label.ID === id);
  return label ? label.name : "未知标签";
};

const store = useStore(Storekey);
const router = useRouter();
const route = useRoute();
const loading = ref(true);

const getlabel = computed(() => {
  return store.state.label?.rows || [];
});
const getteam = computed(() => {
  return store.state.team?.rows || [];
});
const getuser = computed(() => {
  return store.state.user;
});
const teamId = computed(() => {
  return Number(getuser.value?.teamid);
});

const myteam = computed(() => {
  return store.state.myteam || {};
});

const isteam = computed({
  get() {
    return Number(route.query.isteam || 0);
  },
  set(y: number) {
    router.push({ query: { order: "top", offset: 0, limit: 20, isteam: y } });
  },
});
const offset = ref(0);
const limit = ref(20);
const pageSizes: number[] = [limit.value, 50, 100, 200, 400, 500];
const sortable = computed(() => {
  return String(route.query.sortable || "asc");
});
const order = computed(() => {
  return String(
    route.query.order || "top"
  ) as keyof Studycodemodel.Iquestionbank;
});
// 重置参数
function reset() {
  offset.value = 0;
}
const activeName = ref<TABSNAME>(TABSNAME.public);
watch(
  () => activeName.value,
  (e) => {
    let tmp = Object.assign({}, tabsQueryCfg[e]);
    // 删除描述
    delete tmp.desc;
    router.push({ query: assign({}, tmp) });
    reset();
    start();
  }
);
const tabName = computed(() => {
  return route.query.tabName as TABSNAME;
});
function search() {
  start();
}
onMounted(() => {
  // 是否从首页跳转
  if (tabName.value) {
    activeName.value = TABSNAME[tabName.value];
  }
  console.log("activeName.value", myteam.value);
  start();
});

const _formInline = reactive<Iobj<Studycodemodel.Iquestionbank>>({
  teamid: [],
  name: "",
  label: "",
});
watch(_formInline, (e) => {
  router.push({
    query: assign({}, route.query, { order: "top", offset: 0, limit: 20 }),
  });
});
const formInline = computed(() => {
  const I: Iobj<Studycodemodel.Iquestionbank> = {
    _order: order.value,
    _offset: offset.value,
    _sortable: sortable.value || "ASC",
    _limit: limit.value,
  };
  if (route.query.purpose) {
    I.purpose = route.query.purpose;
  }
  if (_formInline.name) {
    // 判断输入的是id还是题单名
    if (_formInline.name == Number(_formInline.name)) {
      I._like = ["ID", _formInline.name];
    } else {
      I._like = ["name", _formInline.name];
    }
  }
  // usertype 只区分 public 和 team
  let usertype = TABSNAME.public;
  if (isteam.value || activeName.value === TABSNAME.team) {
    usertype = TABSNAME.team;
    I.teamid = teamId.value ? teamId.value : getteam.value.map((v) => v.ID);
  }
  I.usertype = usertype;
  // 动态Tab
  if (isDynamicTab.value) {
    // 获取当前动态标签的ID并添加到like查询条件中
    const labelId = currentLabelId.value;
    return {
      ...I,
      _json: [
        {
          field: "label",
          value: [labelId],
          path: "$[*]",
          operator: "contains",
        },
      ],
    };
  }
  return I;
});
watch(formInline, (e) => {
  start();
});
async function start() {
  await debouncet1.value();
}
const getquestionbank = ref<Studycodemodel.Iquestionbank[]>([]);
const getquestionbankcount = ref(0);
const debouncet1 = ref(
  debounce(async () => {
    loading.value = true;
    try {
      if (activeName.value === TABSNAME.myQuestionBank) {
        let cond = { ...formInline.value };
        delete cond.usertype;
        const { rows, count } = await asyncgetmyquestionbank(cond);
        getquestionbank.value = rows;
        getquestionbankcount.value = count;
      } else {
        const { rows, count } = await asyncselectquestionbank(formInline.value);
        getquestionbank.value = rows;
        getquestionbankcount.value = count;
      }
      getquestionbank.value = await formatterData(getquestionbank.value);
    } catch (e) {
      console.error("catch error=>", e);
    }
    loading.value = false;
  }, 300)
);

// 获取题单
async function formatterData(data: Studycodemodel.Iquestionbank[]) {
  const questions = data
    .map((t) => t.questionquestionbank?.map((f) => f.questionid))
    .flat();
  const questionlabels = await asyncselectquestionlabel({
    questionid: questions,
  });
  return data.map((e) => {
    const { questionquestionbank } = e;
    const questionlabel =
      questionquestionbank
        ?.map((t) => {
          const { questionid } = t;
          return questionlabels.rows.filter((t) => t.questionid === questionid);
        })
        .flat() || [];
    return assign(e, {
      questionlabel: uniqBy(questionlabel, (e) => e.labelid),
    });
  });
}

async function del(ID?: number) {
  if (ID) {
    ElMessageBox.confirm("你确定要删除此题吗", "提示").then(async () => {
      try {
        await asyncdelquestionbank({ ID });
        ElMessage.success("删除成功");
        start();
      } catch (e: any) {
        ElMessage.error(e);
      }
    });
  }
}

function changePage(r: number) {
  offset.value = (r - 1) * limit.value;
}
const handleSizeChange = (val: number) => {
  limit.value = val;
  start();
};
// AC率
function getACRate(row: Studycodemodel.Iquestionbank) {
  return row.questionquestionbank?.length
    ? Math.floor(
        (Number(row.ACcount || 0) / Number(row.questionquestionbank?.length)) *
          100
      )
    : 0;
}
function rowClick(row: Studycodemodel.Iquestionbank) {
  router.push({
    name: "题库列表",
    params: { ID: row.ID },
    query: { istest: route.query.istest },
  });
}

// 添加团队专题
const dialogVisible = ref(false);
async function addclick(v: Studycodemodel.Iquestionbank) {
  await asyncaddquestionbankteam({ questionbankid: v.ID, teamid: teamId.value })
    .then(() => {
      dialogVisible.value = false;
      ElMessage.success("添加成功");
    })
    .catch((f) => {
      ElMessage.error(f);
    });
}

function beforeClose() {
  start();
  dialogVisible.value = false;
}
</script>

<style scoped>
.container-box {
  padding: var(--container-margin) 5% 0;
  margin: var(--container-margin) 0rem 0 0rem;
  /* 外边距 */
  --container-margin: 20px;
  --container-header-height: 16vh;
  --container-bg-color: #fff;
}

.container-header {
  /* margin-top: var(--container-margin); */
  height: var(--container-header-height);
  min-height: var(--container-header-height);
  width: 100%;
  padding: 0;

  box-shadow: var(--container-box-shadow);
}

.container-header-form {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  /* height: calc(var(--container-header-height) - var(--el-tabs-item-height)); */
  height: auto;
  padding: 10px 0 15px 0;
}

.container-header-form-item {
  font-weight: 700;
  text-align: left;
  margin: 10px 0;
  --color-43: #000;
}

.container-header-form-item .el-button.is-text {
  border-width: 1px;
}

.container-header-form-item .el-button--default:active {
  border-color: transparent;
}

.container-header-form-item-flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.container-content {
  margin-top: var(--container-margin);
  background: var(--container-bg-color);
  padding: var(--container-margin);
  min-width: 80%;
}

.container-content .pager {
  margin: var(--container-margin);
  margin-right: 0;
  margin-bottom: 0;
  float: right;
}
</style>

<style>
.bg-43 {
  background-color: var(--color-43) !important;
  color: #ffffff !important;
  border-radius: 0px 2px 2px 0px !important;
}

#tabs .el-tabs__item {
  height: 50px !important;
  line-height: 50px;
}
</style>
